package com.wqc.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching//开启注解驱动的缓存管理
public class RedisConfig extends CachingConfigurerSupport {

    private static Logger LOGGER = LoggerFactory.getLogger(CacheConfig.class);

    @Value("${spring.application.name}")
    private String applicationName;

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(factory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        //只需设置string和hash两种即可，因为set list和string是一样的
        // 设置string类型的key-value序列化类型
        redisTemplate.setKeySerializer(new StringRedisSerializer()); // key的序列化类型
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value的序列化类型

        // 设置hash类型的 key-hashkey-value序列化类型
        //redisTemplate.setKeySerializer(new StringRedisSerializer()); // key的序列化类型, 前面若已设置则注释
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        //redisTemplate.afterPropertiesSet(); //这个似乎不写也没问题
        return redisTemplate;
    }

    /**
     * 配置缓存管理器
     * @param redisConnectionFactory 连接工厂
     * @param cacheKeyPrefix 缓存key的前缀
     * @return
     */
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, CacheKeyPrefix cacheKeyPrefix) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        //取出数据序列化配置
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(mapper);
        //存入数据序列化配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                //配置缓存失效时间10min
                .entryTtl(Duration.ofSeconds(600))
                //缓存key的前缀
                .computePrefixWith(cacheKeyPrefix)
                //key序列化方式
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                //value序列化方式
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));

        RedisCacheManager cacheManager = RedisCacheManager
                .builder(redisConnectionFactory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }

    /**
     * 缓存key前缀，spring项目名:{cacheNames}
     * @return
     */
    @Bean
    public CacheKeyPrefix cacheKeyPrefix() {
        return cacheName -> {
            StringBuilder sb = new StringBuilder(100);
            //spring项目名
            sb.append(applicationName).append(":");
            //缓存名（用户自定义）
            sb.append(cacheName).append(":");
            return sb.toString();
        };
    }

    /**
     * 缓存仅仅是为了业务更快地查询而存在的，如果因为缓存操作失败导致正常的业务流程失败，有点得不偿失了。
     * 因此需要开发者自定义CacheErrorHandler处理缓存读写的异常。
     *
     * 添加自定义缓存异常处理
     * 当缓存读写异常时,忽略且不抛出异常，将继续执行业务
     * 比如redis停止后，@Cacheable注解的方法会抛出异常，read timeout 异常导致正常业务流程失败。
     */
    @Override
    public CacheErrorHandler errorHandler() {
        return new IgnoreExceptionCacheErrorHandler();
    }
}
